#!/usr/bin/env python
# encoding: utf-8
# @author: Lin Han
# @contact: voldemort22@126.com
# @file: migrate_db.py
# @time: 2021/6/28 10:29
# @desc:
import json
from pymongo import MongoClient

OLD_BACKEND_IP = "161.189.75.127"
BACKEND_IP = "106.14.173.159"

old_client = MongoClient(f"mongodb://linhan:linhan1987@{OLD_BACKEND_IP}:27017/")
old_db = old_client["do_center"]
old_coll_names = old_db.list_collection_names(session=None)

client = MongoClient(f"mongodb://linhan:linhan1987@{BACKEND_IP}:27017/")
db = client["do_center"]
coll_names = db.list_collection_names(session=None)


for i in old_coll_names:
    collection = old_db[i]
    output = []
    for l in collection.find():
        print(l)
        if "_id" in l.keys():
            l.pop("_id")
        output.append(l)
    with open(f'{i}.json', 'w', encoding="UTF-8") as jf:
        jf.write(json.dumps(output, indent=4))
    new_collection = db[i]
    if i in coll_names:
        with open(f'{i}.json', encoding="UTF-8") as jf:
            str = jf.read()
            data = []
            data.extend(json.loads(str))
            new_collection.insert_many(data)
